﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.Win32;

namespace ImplementNavigation
{
    internal class AssemblyResolve
    {
        private static readonly string s_u8Root;
        private static readonly string s_u8MPath;
        private static readonly string s_u8FrameworkPath;
        private static readonly string s_u8APIFramework;
        static AssemblyResolve()
        {
            //取U8安装路径
            s_u8Root = __GetU8InstallPath();
            s_u8MPath = s_u8Root + @"U8M\";
            s_u8FrameworkPath = s_u8Root + @"Framework\";
            s_u8APIFramework = s_u8Root + @"UFMOM\U8APIFramework\";

            //给当前AppDomain添加缺少程序集全局事件，当前AppDomain碰到缺少程序集时都会触发此事件。
            AppDomain.CurrentDomain.AssemblyResolve += __CurrentDomain_AssemblyResolve;
        }
        const string Product_Registry_InstallKey = "SOFTWARE\\Ufsoft\\WF\\V8.700\\Install\\CurrentInstPath";

        private static string __GetU8InstallPath()
        {
            string root;
            RegistryKey installPath = Registry.LocalMachine.OpenSubKey(Product_Registry_InstallKey);
            if (installPath == null)
                root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            else
                root = installPath.GetValue(String.Empty).ToString();
            return root += @"\";
        }

        /// <summary>
		/// 缺少程序集全局处理事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		/// <returns></returns>
		private static Assembly __CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            //先在已经加载的程序集中选择
            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (args.Name.Equals(asm.FullName))
                    return asm;
            }

            //取未加载的DLL名
            string sAsmName = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";

            Debug.WriteLine(sAsmName);
            //到指定的目录下找
            if (File.Exists(s_u8Root + sAsmName))
                return Assembly.LoadFrom(s_u8Root + sAsmName);
            if (File.Exists(s_u8MPath + sAsmName))
                return Assembly.LoadFrom(s_u8MPath + sAsmName);
            if (File.Exists(s_u8FrameworkPath + sAsmName))
                return Assembly.LoadFrom(s_u8FrameworkPath + sAsmName);
            if (File.Exists(s_u8APIFramework + sAsmName))
                return Assembly.LoadFrom(s_u8APIFramework + sAsmName);
            return null;
        }

    }
}
